package com.hwh.traffic.fragment;


import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.model.LatLng;

import com.hwh.traffic.MapApplication;
import com.hwh.traffic.R;
import com.hwh.traffic.activity.BusInfoActivity;
import com.hwh.traffic.activity.StopInfoActivity;
import com.hwh.traffic.adapter.AutoCompleteAdapter;
import com.hwh.traffic.busEntity.Record;
import com.hwh.traffic.db.TrafficLab;
import com.hwh.traffic.utils.BusApiUtil;
import com.hwh.traffic.utils.ButtonUtil;
import com.hwh.traffic.utils.DensityUtil;
import org.apache.commons.lang3.StringUtils;
import java.util.LinkedList;
import java.util.List;

public class MainFragment extends Fragment {



    private AutoCompleteTextView main_page_edit;
    private Button main_page_search;
    private MapApplication mapApplication;
    private LatLng latLng;
    private String routeName;
    private String[] busApi; //实时公交API
    private TrafficLab trafficLab;
    private LinearLayout bus_search_list;

    public MainFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_main, container, false);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mapApplication = (MapApplication) getActivity().getApplication();
        trafficLab = mapApplication.getTrafficLab();
        latLng = mapApplication.getLatLng();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initViews();

    }

    private void initViews() {

        main_page_edit = getView().findViewById(R.id.main_page_edit);
        main_page_search = getView().findViewById(R.id.main_page_search);
        main_page_search.setOnClickListener(v -> {
            //防止用户快速点击
            if (ButtonUtil.isFastDoubleClick()) {
                return;
            }
            if (StringUtils.isEmpty(main_page_edit.getText().toString())) {
                Toast.makeText(getActivity(), "请输入正确的站点或路线", Toast.LENGTH_SHORT).show();
            } else {
                routeName = StringUtils.trim(main_page_edit.getText().toString());
                //判断是否定位成功
                latLng = mapApplication.getLatLng();
                busApi = BusApiUtil.getBusApi(routeName, trafficLab, latLng);
                if (busApi == null) {
                    //判断是否是站点
                    String stopName = main_page_edit.getText().toString();
                    LinkedList<Long> list = (LinkedList<Long>) trafficLab.findStopIdByName(stopName);
                    if (list == null || list.size() == 0) {
                        Toast.makeText(getActivity(), "请输入正确的站点或路线", Toast.LENGTH_SHORT).show();
                        return;
                    } else {
                        String api = "https://app.ibuscloud.com/v11/bus/getNextBusByStopId?stopId=" + list.get(0) + "&city=350100&userLat=26.074268&userLng=119.296389&h5Platform=7&appSource=com.ibuscloud.fuzhou&token=A90D8DAFD7A63935BC56F082D3199577F817446F070B2C616E9E95596BD54E26838F32346AE558809B381C35E3AD3871&radius=1000&lat=26.074268&lng=119.296389&uuid=fbdb87b5-1ea9-3259-87f3-69ceeefdde31";
                        Intent intent = new Intent(getActivity(), StopInfoActivity.class);
                        intent.putExtra("STOP_API", api);
                        intent.putExtra("STOP_NAME", stopName);
                        startActivity(intent);
                    }

                } else {
                    Intent intent = new Intent(getActivity(), BusInfoActivity.class);
                    intent.putExtra("BUS_API", busApi);
                    intent.putExtra("ROUTE_NAME", routeName);
                    startActivity(intent);
                }
            }

        });

        //自定义自动提示适配器
        AutoCompleteAdapter autoCompleteAdapter = new AutoCompleteAdapter(getActivity(), android.R.layout.simple_dropdown_item_1line,null, new String[]{"name"}, new int[]{android.R.id.text1},0);
        main_page_edit.setAdapter(autoCompleteAdapter);
        //设置输入一个字符就开始提示
        main_page_edit.setThreshold(1);


        showSearchList();

    }

    private void showSearchList() {
        bus_search_list = getView().findViewById(R.id.main_page_searchlist);
        bus_search_list.removeAllViews();
        new Thread(() -> {
            List<Record> recordList = trafficLab.findAllRecord();
            getActivity().runOnUiThread(() -> {
                for (Record record : recordList) {
                    //渲染搜索历史
                    LinearLayout mLinearLayout = new LinearLayout(getActivity().getApplicationContext());
                    ImageView delete_img = new ImageView(getActivity().getApplicationContext());
                    TextView search_text = new TextView(getActivity().getApplicationContext());

                    bus_search_list.addView(mLinearLayout);
                    mLinearLayout.addView(search_text);
                    mLinearLayout.addView(delete_img);

                    ViewGroup.LayoutParams lp_LinearLayout = mLinearLayout.getLayoutParams();
                    lp_LinearLayout.width = ViewGroup.LayoutParams.MATCH_PARENT;
                    lp_LinearLayout.height = ViewGroup.LayoutParams.WRAP_CONTENT;
                    mLinearLayout.setGravity(Gravity.CENTER);
                    mLinearLayout.setOrientation(LinearLayout.HORIZONTAL);
                    mLinearLayout.setLayoutParams(lp_LinearLayout);

                    LinearLayout.LayoutParams lp_TextView = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
                    lp_TextView.height = ViewGroup.LayoutParams.WRAP_CONTENT;
                    lp_TextView.width = DensityUtil.dip2px(getActivity().getApplicationContext(), 340);
                    int dp_20 = DensityUtil.dip2px(getActivity().getApplicationContext(), 20);
                    int dp_10 = DensityUtil.dip2px(getActivity().getApplicationContext(), 10);
                    search_text.setTextSize(15);
                    search_text.setPadding(dp_20, dp_10, 0, dp_10);
                    search_text.setTextColor(Color.BLACK);
                    search_text.setText(record.getSearch_route().replace("路","") + "路  方向  " + record.getSearch_end());
                    search_text.setOnClickListener(v -> {
                        latLng = mapApplication.getLatLng();
                        BusApiUtil.toBusInfoList(latLng,getActivity(),record.getSearch_route(),trafficLab);
                    });

                    search_text.setLayoutParams(lp_TextView);

                    ViewGroup.LayoutParams lp_ImageView_point = delete_img.getLayoutParams();
                    lp_ImageView_point.width = ViewGroup.LayoutParams.WRAP_CONTENT;
                    lp_ImageView_point.height = ViewGroup.LayoutParams.WRAP_CONTENT;
                    delete_img.setImageResource(R.drawable.delete);
                    delete_img.setPadding(0, 0, dp_10, 0);
                    delete_img.setOnClickListener(v -> {
                        trafficLab.deleteRecord(record.getRecord_id());
                        LinearLayout linearLayout = (LinearLayout) delete_img.getParent();
                        linearLayout.setVisibility(View.GONE);
                    });

                }
            });
        }).start();

    }


}
